package com.library.relation.dao;

import com.framework.BaseDao;
import com.library.entity.StaffRelation;
import com.library.entity.Staff;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class StaffRelationDaoImpl extends BaseDao<StaffRelation,String> {
	@Resource
	private SessionFactory sessionFactory;

	//查找与staff有关的全部关系
	public List<StaffRelation> findByStaff(Staff staff){
		try{
			return super.findByProperty("from StaffRelation sr where sr.staffOne=? or sr.staffTwo=?", new Object[]{staff,staff});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public List<StaffRelation> findByStaffOrderByCountDesc(Staff staff){
		Object[] params = new Object[]{staff};
		String hql = "from StaffRelation sr where sr.staffOne=? and sr.staffOne != sr.staffTwo order by sr.count desc";
		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		query.setMaxResults(6);	//最大查询为6

		if (params != null && params.length > 0) {
			for (int i = 0; i < params.length; i++) {
				query.setParameter(i, params[i]);
			}
		}

		return query.list();
	}

	public StaffRelation findByStaffAndStaff(Staff s1, Staff s2){
		try{
			return super.findOne("from StaffRelation sr where sr.staffOne=? and sr.staffTwo=?", new Object[]{s1,s2});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public StaffRelation getRelationById(Integer relationId){
		try{
			return super.get(relationId);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public void saveRelation(StaffRelation relation){
		try {
			this.save(relation);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateRelation(StaffRelation relation){
		try {
			this.update(relation);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<StaffRelation> getAll(){
		try{
			return super.findByProperty("from StaffRelation", new Object[]{});
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public void deleteRelation(StaffRelation relation){
		try {
			this.delete(relation);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
